package com.lxs.doc.rocess.common;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.model.StyleDescription;
import org.apache.poi.hwpf.model.StyleSheet;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DocOutlineUtils {
    /**
     * 提取文档大纲信息
     */
    public static DocOutlineInfo extractOutlineInfo(String filePath) {
        DocOutlineInfo info = new DocOutlineInfo();

        try (FileInputStream fis = new FileInputStream(filePath);
             HWPFDocument document = new HWPFDocument(fis)) {

            Range range = document.getRange();
            info.totalParagraphs = range.numParagraphs();

            // 解析大纲段落
            parseOutlineParagraphs(range, info);

            // 解析样式信息
            parseStyleInfo(document, info);

            // 解析文档属性
            parseDocumentProperties(document, info);

        } catch (IOException e) {
            System.err.println("解析文档失败: " + e.getMessage());
        }

        return info;
    }

    private static void parseOutlineParagraphs(Range range, DocOutlineInfo info) {
        for (int i = 0; i < range.numParagraphs(); i++) {
            Paragraph paragraph = range.getParagraph(i);
            String text = paragraph.text().trim();

            if (text.isEmpty()) {
                info.emptyParagraphs++;
                continue;
            }

            OutlineParagraph op = new OutlineParagraph();
            op.index = i;
            op.text = text;
            op.level = paragraph.getLvl();
            op.styleIndex = paragraph.getStyleIndex();
            op.isHeading = isHeadingParagraph(paragraph);
            op.startOffset = paragraph.getStartOffset();
            op.endOffset = paragraph.getEndOffset();

            info.paragraphs.add(op);

            if (op.isHeading) {
                info.headingCount++;
                info.headingsByLevel.put(op.level,
                        info.headingsByLevel.getOrDefault(op.level, 0) + 1);
            }
        }
    }

    private static void parseStyleInfo(HWPFDocument document, DocOutlineInfo info) {
        StyleSheet styleSheet = document.getStyleSheet();
        if (styleSheet != null) {
            for (int i = 0; i < styleSheet.numStyles(); i++) {
                StyleDescription style = styleSheet.getStyleDescription(i);
                if (style != null && style.getName() != null) {
                    info.styles.put(i, style.getName());
                }
            }
        }
    }

    private static void parseDocumentProperties(HWPFDocument document, DocOutlineInfo info) {
        info.characterCount = document.getCharacterTable().getTextRuns().size();
        info.bookmarkCount = document.getBookmarks().getBookmarksCount();
    }

    private static boolean isHeadingParagraph(Paragraph paragraph) {
        // 多种条件判断是否为标题
        int level = paragraph.getLvl();
        String text = paragraph.text().trim();

        return level > 0 ||
                (text.length() < 50 && !text.contains("。")) ||
                paragraph.getStyleIndex() >= 1 && paragraph.getStyleIndex() <= 6;
    }

    // 数据结构类
    public static class DocOutlineInfo {
        public int totalParagraphs;
        public int emptyParagraphs;
        public int headingCount;
        public int characterCount;
        public int bookmarkCount;
        public List<OutlineParagraph> paragraphs = new ArrayList<>();
        public Map<Integer, String> styles = new HashMap<>();
        public Map<Integer, Integer> headingsByLevel = new HashMap<>();

        public void printSummary() {
            System.out.println("=== 文档大纲摘要 ===");
            System.out.printf("总段落数: %d%n", totalParagraphs);
            System.out.printf("空段落数: %d%n", emptyParagraphs);
            System.out.printf("标题数量: %d%n", headingCount);
            System.out.printf("字符总数: %d%n", characterCount);
            System.out.printf("书签数量: %d%n", bookmarkCount);

            System.out.println("各级标题分布:");
            headingsByLevel.forEach((level, count) ->
                    System.out.printf("  级别 %d: %d 个%n", level, count));
        }
    }

    public static class OutlineParagraph {
        public int index;
        public String text;
        public int level;
        public int styleIndex;
        public boolean isHeading;
        public int startOffset;
        public int endOffset;
    }
}
